<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class entity_model extends CI_Model
{
    private $dbName = '';
    private $arrDatabase = '';
    
    public function __construct()
    {
        parent::__construct();
        $this->dbName = $this->db->database;
        $this->arrDatabase = $this->getAll_PKKey_FKKey();
    }    
    
    public function getAll_PKKey_FKKey()
    {
        $sql = "SELECT
            ke.TABLE_NAME, ke.COLUMN_NAME, ke.REFERENCED_TABLE_NAME, ke.REFERENCED_COLUMN_NAME
            FROM information_schema.KEY_COLUMN_USAGE ke
            WHERE ke.referenced_table_name IS NOT NULL AND CONSTRAINT_SCHEMA = '".$this->dbName."'
            ORDER BY ke.referenced_table_name";
        $query = $this->db->query($sql);
        $arrDatabase = $query->result_array();
        return $arrDatabase;
    }
    
    public function FKKey($tableName)
    {
        $arrDatabase = $this->arrDatabase;
        $str = '';
        $strFK = '';
        foreach ($arrDatabase as $row) {
            if ($row['TABLE_NAME'] == $tableName) {
                $tbl = $row['REFERENCED_TABLE_NAME'];
                $tid = $row['COLUMN_NAME'];
                $id = $row['REFERENCED_COLUMN_NAME'];
                $str .= '
    public function checkExist_'.$tbl.'($'.$tid.')
    {
        $query = $this->db->get_where("'.$tbl.'", array("'.$id.'" => $'.$tid.'));
        if ($query->num_rows() > 0) {
            return true;
        }
        return false;
    }
    ';
                $strFK .= '
        // foreign key check
        if (!isset($params["'.$tid.'"]) || !$this->checkExist_'.$tbl.'($params["'.$tid.'"])) {
            return -1;
        }';
            }
        }
        return array($str, $strFK);        
    }   
    
    public function PKKEY($tableName)
    {
        $arrDatabase = $this->arrDatabase;
        $str = '';
        $strPK = '';
        $i = -1;
        foreach ($arrDatabase as $row) {
            if ($row['REFERENCED_TABLE_NAME'] == $tableName) {
                $tbl = $row['TABLE_NAME'];
                $tid = $row['COLUMN_NAME'];
                $id = $row['REFERENCED_COLUMN_NAME'];
                $str .= '
    public function checkExistFK_'.$tbl.'($'.$id.')
    {
        $query = $this->db->get_where("'.$tbl.'", array("'.$tid.'" => $'.$id.'));
        if ($query->num_rows() > 0) {
            return true;
        }
        return false;
    }
    ';
        $strPK .= '// check exist foreign key
        if ($this->checkExistFK_'.$tbl.'($'.$id.')) {
            return '.$i.';
        }
        ';
            $i--;
            }
        }
        return array($str, $strPK);     
    }
}